package com.tsd.common.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.HttpResult;
import com.tsd.core.utils.HttpUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * @ClassName: ForwardController
 * @Description: TODO
 * @Author: Luoyc
 * @Date: 2020/1/16 13:38
 * @Version: 1.0
 */
@Controller
@Scope("prototype")
@RequestMapping("/api/v2")
public class ForwardController extends BaseController {

    @ResponseBody
    @RequestMapping(value = "/forward.action", method = RequestMethod.POST)
    public HttpResult<Object> forward() {
        HttpResult<Object> hr = new HttpResult<Object>();
        try {
            Map<String, Object> map = super.getParams(request);
            String url = HlpUtils.getString(map, "url");
            String result = HttpUtil.postData(url, JSON.toJSONString(map));
            JSONObject object = JSON.parseObject(result);
            boolean ok = object.getBoolean("ok");
            if (ok) {
                hr.setData(object.get("data"));
                hr.setCode(ErrorCode.CODE_SUCCESS);
            } else {
                throw new HlpException(object.getString("message"));
            }
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }
}
